package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    SystemUserMapper systemUserMapper;


    @Override
    public CaptchaVo captcha() {
        //1.创建验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130,70,4); //图片验证码对象
        specCaptcha.setCharType(SpecCaptcha.TYPE_DEFAULT);
        String captchaCode = specCaptcha.text().toLowerCase(); // 验证码值全小写

        String iamge = specCaptcha.toBase64(); //图片经过Base64进行编码字符串

        //2.声明redis的key,验证码的值存储在redis中，用于登录校验。
        String captchaKey = RedisConstant.ADMIN_LOGIN_PREFIX+ UUID.randomUUID().toString().replaceAll("-","");
        stringRedisTemplate.opsForValue().set(captchaKey,captchaCode,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //3.封装vo对象
        CaptchaVo vo = new CaptchaVo(iamge,captchaKey);

        //4.返回数据
        return vo;
    }


    @Override
    public String login(LoginVo loginVo) {
        //1.校验表单参数验证码是否为空
        String formCaptchaCode = loginVo.getCaptchaCode();
        if(!StringUtils.hasText(formCaptchaCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        //2.从缓存中获取校验码，判断是否过期了
        String formCaptchaKey = loginVo.getCaptchaKey();
        //默认  1分钟
        String redisCaptchaCode = stringRedisTemplate.opsForValue().get(formCaptchaKey); //  admin:login:70415dc9b14443e3bb4825d2a8d7bff8
        if(!StringUtils.hasText(formCaptchaCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //3.判断输入的校验码和缓存的校验码是否一致
        if(!formCaptchaCode.equalsIgnoreCase(redisCaptchaCode)){ //忽略大小写比较。缓存中存储是小写
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        //4.根据用户名称查询数据库，判断用户是否存在

        //账号名称不能重复的。数据库表字段设计：   UNIQUE约束
        SystemUser systemUser = systemUserMapper.selectSystemUserByUsername(loginVo.getUsername());
        if(systemUser==null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //5.判断用户账号是否被禁用
        if(systemUser.getStatus().getCode().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //6.判断密码是否正确
        if(!systemUser.getPassword().equalsIgnoreCase(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //7.生成令牌
        //eyJhbGciOiJIUzI1NiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAA_6tWKi5NUrJSCg12DYr39HPzV9JRSq0oULIyNDcxszQ2MzEz01EqLU4t8kwBikGYeYm5qUAtiSm5mXlKtQBD2CIzQgAAAA.L-wJmrtNdyBF0rzoZj5Zoa_zbjMh-CFacqeNOZmXTKI
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());

        //8.返回令牌
        return token;
    }


    @Override
    public SystemUser info(Long userId) {
        return systemUserMapper.selectById(userId);
    }
}
